'use strict'

// const {defineConfig} = require('@vue/cli-service')
// const TerserPlugin = require('terser-webpack-plugin')

const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin
function resolve(dir) {
  return path.resolve(__dirname, dir)
}
// function generatePlugin() {
//   if (isDevEnv) return []
//   return [
//     new TerserPlugin({
//       parallel: true,
//       exclude: /node_modules/,
//       terserOptions: {
//         ecma: undefined,
//         warnings: false,
//         parse: {},
//         compress: {
//           drop_console: true,
//           drop_debugger: true,
//           pure_funcs: ['console.log'],
//         },
//       },
//     }),
//   ]
// }
const getCurrentTime = (dat) => {
  const year = dat.getFullYear()
  const mon =
    dat.getMonth() + 1 < 10 ? `0${dat.getMonth() + 1}` : dat.getMonth() + 1
  const data = dat.getDate() < 10 ? `0${dat.getDate()}` : dat.getDate()
  const hour = dat.getHours() < 10 ? `0${dat.getHours()}` : dat.getHours()
  const min = dat.getMinutes() < 10 ? `0${dat.getMinutes()}` : dat.getMinutes()
  const seon = dat.getSeconds() < 10 ? `0${dat.getSeconds()}` : dat.getSeconds()
  const newDate = `${year}-${mon}-${data} ${hour}: ${min}: ${seon}`
  return newDate
}
const isDevEnv = false
const now = Date.now()
const onlineTime = new Date(now + 8 * 60 * 1000)
const localTime = new Date(now)
const dateObj = isDevEnv ? localTime : onlineTime
const preffix = process.env.NODE_ENV === 'development' ? '' : ''
const cdn = {
  externals: {
    // vue: 'Vue',
    // Vuex: 'Vuex',
    // 'vue-router': 'vueRouter',
    // axios: 'Axios',
    // dayjs: 'Dayjs',
    // 'element-ui': 'ELEMENT',
  },
  // css: [`${preffix}/static/css/element-ui@2.15.14.min.css`],
  js: [
    // '/static/js/vue@2.6.14.js',
    // '/static/js/element-ui@2.15.14.min.js',
    // '/static/js/vue-router@3.5.1.min.js',
    // '/static/js/axios&element-ui-i18n&dayjs&vuex&nprogress.min.js',
  ],
}
const { name } = require('./package.json')

class VersionPlugin {
  constructor(options) {
    this.buildAt = options.build_at
  }
  apply(compiler) {
    compiler.hooks.done.tap('versionPlugin', () => {
      try {
        fs.writeFileSync('./dist/version', this.buildAt)
      } catch (error) {}
    })
  }
}
class PrintBuildTimePlugin {
  apply(compiler) {
    compiler.hooks.done.tap('PrintBuildTimePlugin', (stats) => {
      console.log('\n')
      console.log(stats.hash)
      console.log('\n')
      console.log(
        chalk.blue(
          `==============Build complete in ${
            stats.endTime - stats.startTime
          } ms==================`
        )
      )
    })
  }
}
const build_at = getCurrentTime(localTime)

module.exports = {
  publicPath: '/', // process.env.NODE_ENV === 'production' ? '/trello/' : '/',
  outputDir: 'dist',
  assetsDir: 'assets',
  productionSourceMap: false,
  filenameHashing: false,
  lintOnSave: false,
  devServer: {
    compress: true,
    hot: true,
    open: true,
    host: 'localhost',
    port: 3000,
    // proxy: {
    //   '': {
    //     target: process.env.VUE_APP_BASE_URL,
    //     changeOrigin: true,
    //     pathRewrite: {
    //       // '^api':'/'
    //     }
    //   }
    // }
  },

  // configureWebpack: (config) => {
  //   Object.assign(config, {
  //     resolve: {
  //       alias: {
  //         '@': path.resolve('./src'),
  //         '@assets': path.resolve('./src/assets'),
  //       },
  //       // fallback: {
  //       //   path: require.resolve('path-browserify'),
  //       //   fs: false,
  //       // },
  //       // alias: {
  //       //   '@': resolve('src'),
  //       // },
  //       // externals: ['.js', '.json', '.vue', 'scss', 'html'],
  //     },
  //     // externals: cdn.externals,
  //     // plugins: generatePlugin(),
  //   })
  // },
  configureWebpack: (config) => {
    return {
      resolve: {
        alias: {
          '@asset': resolve('./src/assets'),
          '@': resolve('./src'),
        },
        // fallback: {
        //   path: require.resolve('path-browserify'),
        //   fs: false,
        // },
      },
      externals: cdn.externals,
    }
  },
  chainWebpack: (config) => {
    config.plugins.delete('preload')
    config.plugins.delete('prefeth')
    config.plugin('define').tap((definitions) => {
      definitions[0]['process.env'].BUILD_AT = JSON.stringify(
        getCurrentTime(localTime)
      )
      definitions[0]['process.env'].VERSION = JSON.stringify(name)
      return definitions
    })
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end()

    config.plugin('html').tap((args) => {
      args[0].cdn = cdn
      return args
    })

    config.optimization.minimizer('terser').tap((args) => {
      args[0].parallel = 4
      args[0].terserOptions.compress.warnings = true
      args[0].terserOptions.compress.drop_debugger = true
      args[0].terserOptions.compress.drop_console = true
      return args
    })
    if (process.env.NODE_ENV === 'development') {
      // config.plugin('bundle-report').use(BundleAnalyzerPlugin, [
      //   {
      //     analyzerMode: 'server', // 分析模式，static生成静态页面
      //     generateStatsFile: true, // 是否生成stats.json文件
      //     statsOptions: 'normal', // 统计信息类型，'none' | 'normal' | 'verbose'
      //     logLevel: 'error', // 日志级别
      //     analyzerHost: 'localhost',
      //     analyzerPort: '4000',
      //     defaultSizes: 'gzip',
      //     openAnalyzer: false, // 是否自动打开分析报告页面 http://127.0.0.1:8888/
      //   },
      // ])
    }
    config.plugin('PrintBuildTimePlugin').use(new PrintBuildTimePlugin())
    config.plugin('versionPlugin').use(new VersionPlugin({ build_at }))
  },
}
